<div id="formDiv"></div>
<script type="text/html" id="warehouseProductionOrderformContent">
  <form
    lay-filter="warehouseProductionOrderForm"
    id="warehouseProductionOrderForm"
    class="layui-form open-form"
  >
    <div class="open-model">
      <div class="open-auto">
        <div>
          <div class="layui-form-item layui-row">
            <input name="id" type="hidden" />
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">选择客户</label>
              <div class="layui-input-block">
                <select
                  id="customerId"
                  name="customerId"
                  lay-filter="customerId"
                ></select>
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">货主订单号</label>
              <div class="layui-input-block">
                <input
                  type="text"
                  class="layui-input"
                  name="ownerOrderNumber"
                />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">交货时间</label>
              <div class="layui-input-block">
                <input
                  type="text"
                  class="layui-input"
                  id="deliveryTime"
                  name="deliveryTime"
                />
              </div>
            </div>

            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">所属合同</label>
              <div class="layui-input-block">
                <select
                  id="contractId"
                  name="contractId"
                  lay-filter="contractId"
                ></select>
              </div>
            </div>
          </div>
          <div class="layui-form-item layui-row">
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">物料总类</label>
              <input
                type="hidden"
                id="remainingProductionSchedule"
                name="remainingProductionSchedule"
              />
              <div class="layui-input-block">
                <input
                  class="layui-input adv-disable"
                  id="materialType"
                  disabled
                  name="materialType"
                />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">总净重</label>
              <div class="layui-input-block">
                <input
                  class="layui-input adv-disable"
                  id="totalWeight"
                  disabled
                  name="totalWeight"
                />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">总加工费</label>
              <div class="layui-input-block">
                <input
                  class="layui-input adv-disable"
                  id="totalProcessingFee"
                  disabled
                  name="totalProcessingFee"
                />
              </div>
            </div>
          </div>
          <!-- {{# if(d.eventName === 'detail'){ }} -->
          <div class="layui-form-item layui-row">
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">提货人</label>
              <div class="layui-input-block">
                <input
                  type="text"
                  class="layui-input adv-disable"
                  id="creatorName"
                  disabled
                  name="creatorName"
                />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">创建时间</label>
              <div class="layui-input-block">
                <input
                  type="text"
                  class="layui-input"
                  id="createTime"
                  disabled
                  name="createTime"
                />
              </div>
            </div>
          </div>
          <!-- {{# } }} -->
        </div>

        <div class="layui-form-item tableContent">
          <!-- {{# if(d.eventName !== 'detail'){ }} -->
          <button class="layui-btn" type="button" id="Configure">
            添加成品信息
          </button>
          <!-- {{# } }} -->
          <table
            class="layui-table"
            id="purchasePlanFormTable"
            lay-filter="purchasePlanFormTable"
          ></table>
        </div>

        <div class="layui-form-item text-right">
          <button
            class="layui-btn layui-btn-primary"
            type="button"
            ew-event="closeDialog"
          >
            关闭
          </button>
          <button
            class="layui-btn"
            lay-filter="formSubmit"
            type="button"
            lay-submit
          >
            提交
          </button>
        </div>
      </div>
    </div>
  </form>
</script>

<script type="text/html" id="purchasePlanFormTableBar">
  <button
    class="layui-btn layui-btn-danger layui-btn-xs"
    lay-event="del"
    type="button"
  >
    删除
  </button>
</script>

<script type="text/html" id="warehouseMaterialRequisitionRecordTableBar">
  <button
    class="layui-btn layui-btn-danger layui-btn-xs"
    lay-event="del111"
    type="button"
  >
    删除
  </button>
</script>

<script type="text/html" id="customerSku">
  <div class="open-form">
    <div class="open-model">
      <div class="open-auto">
        <button class="layui-btn " id="addCustomerSku">确认选择</button>
        <table class="layui-table" id="customerSkuTable"></table>
      </div>
    </div>
  </div>
</script>

<script type="text/html" id="warehouseMaterialRequisitionRecordForm">
  <div class="open-form">
    <div class="open-model">
      <div class="open-auto">
        <button class="layui-btn " id="addMaterialInfo">添加材料信息</button>
        <table
          class="layui-table"
          id="warehouseMaterialRequisitionRecordTable"
          lay-filter="warehouseMaterialRequisitionRecordTable"
        ></table>
      </div>
      <div class="layui-form-item text-right">
        <button
          class="layui-btn"
          id="saveMaterialInfo"
          type="button"
          lay-submit
        >
          保存
        </button>
        <button
          class="layui-btn layui-btn-primary"
          type="button"
          ew-event="closeDialog"
        >
          关闭
        </button>
      </div>
    </div>
  </div>
</script>
<script>
  layui.use(
    ["layer", "form", "table", "admin", "laydate", "upload", "laytpl"],
    async function () {
      var $ = layui.jquery;
      var layer = layui.layer;
      var form = layui.form;
      var table = layui.table;
      var config = layui.config;
      var admin = layui.admin;
      var upload = layui.upload;
      let laydate = layui.laydate;
      let laytpl = layui.laytpl;
      const nowData = { ...parentData };
      let data = nowData?.data;
      let skuList = [];
      laytpl(warehouseProductionOrderformContent.innerHTML).render(
        { ...nowData },
        function (html) {
          $("#formDiv").after(html);
        }
      );
      // 初始化日期选择
      laydate.render({
        elem: "#deliveryTime",
        type: "datetime",
      });
      // 初始化客户选择
      await admin.initDataSelectPro(
        "enterprise/sell/admin/customersInfo/list",
        { limit: 99999 },
        "customerId",
        "客户名称",
        (d) => {
          $("#contractId").empty();
          $("#contractId").val("");
          if (d.value) {
            admin.req(
              "warehouse/warehouse/contract/list",
              { warehouseCustomerId: d.value },
              (res) => {
                if (res.code == 200) {
                  admin.initDataSelect(
                    res.data,
                    {},
                    "contractId",
                    null,
                    "合同编号",
                    "contractName"
                  );
                }
              }
            );
          }
        },
        "customerName"
      );

      // 品种列表
      const productVarietyData = await admin.reqPro(
        "warehouse/warehouse/product/list",
        { limit: 99999 }
      );
      const productVarietyList = productVarietyData.data;

      if (nowData.eventName === "detail") {
        admin.setFormDisable("#warehouseProductionOrderForm", true);
      }

      const tableVal = table.render({
        elem: "#purchasePlanFormTable",
        page: false,
        limit: 999999,
        //   height: 400,
        data: [],
        cols: [
          [
            { type: "numbers", title: "序号" },
            { field: "productVariety", align: "center", title: "品种" },
            { field: "productCode", align: "center", title: "客户成品料号" },
            { field: "productSpecCode", align: "center", title: "规格" },
            { field: "diameter", align: "center", title: "厚度/壁厚/直径" },
            { field: "width", align: "center", title: "宽度/外径" },
            { field: "length", align: "center", title: "长度" },
            { field: "productMainUnit", align: "center", title: "成品单位" },
            //   { field: "netWeight", align: "center", title: "净重" },
            //   { field: "price", align: "center", title: "价格" },
            {
              field: "requiredQuantity",
              align: "center",
              title: "需求数",
              templet: admin.setTableInput(
                "requiredQuantity",
                nowData.eventName === "detail",
                "requiredQuantity"
              ),
            },
            {
              field: "materialNumber",
              align: "center",
              title: "材料料号",
              templet: function (d) {
                return (
                  '<button class="layui-btn " lay-event="materialDetail" type="button">' +
                  (d.materialNumber ? d.materialNumber : "无物料") +
                  "</button>"
                );
              },
            },
            {
              field: "processingDrawing",
              align: "center",
              title: "加工图纸",
              templet: admin.setTableUpload(
                "processingDrawing",
                nowData.eventName == "detail"
              ),
            },
            {
              field: "remark",
              align: "center",
              title: "加工备注",
              templet: admin.setTableInput(
                "remark",
                nowData.eventName === "detail",
                "remark"
              ),
            },
            {
              align: "center",
              toolbar: "#purchasePlanFormTableBar",
              title: "操作",
              width: 100,
              hide: nowData.eventName === "detail",
            },
          ],
        ],
        done: function () {
          admin.tableInputChangeByClass(
            "purchasePlanFormTable",
            "remark",
            () => {}
          );
          admin.tableInputChangeByClass(
            "purchasePlanFormTable",
            "requiredQuantity",
            (index, value, tableData, field, tableId) => {
              console.log(index, value, tableData, field, tableId);
              form.val("warehouseProductionOrderForm", {
                totalWeight: tableData.reduce(
                  (acc, curr) =>
                    acc + curr.netWeight * (curr.requiredQuantity || 0),
                  0
                ),
                totalProcessingFee: tableData.reduce(
                  (acc, curr) =>
                    acc + curr.price * (curr.requiredQuantity || 0),
                  0
                ),
              });
            }
          );
          if (nowData.eventName === "detail") {
          } else {
            form.val("warehouseProductionOrderForm", {
              materialType: table.cache["purchasePlanFormTable"].length,
              totalWeight: table.cache["purchasePlanFormTable"].reduce(
                (acc, curr) =>
                  acc + curr.netWeight * (curr.requiredQuantity || 0),
                0
              ),
              totalProcessingFee: table.cache["purchasePlanFormTable"].reduce(
                (acc, curr) => acc + curr.price * (curr.requiredQuantity || 0),
                0
              ),
            });
          }
          // class为requiredQuantity的限制输入数字
          $(".requiredQuantity").attr("type", "number");
          upload.render({
            elem: ".upload-btn", // 绑定上传按钮
            url: config.upload_url + "uploadFile",
            accept: "file", // 可接受的文件类型
            headers: { Authorization: "Bearer " + config.getToken() },
            done: function (res, index, upload) {
              // 上传成功的回调
              if (res.code === 200) {
                // 更新表格缓存中的数据
                const button = $(this.item);
                const index = button.data("index");
                let tableData = table.cache["purchasePlanFormTable"];
                let rowIndex = tableData.findIndex(
                  (v) => v["LAY_TABLE_INDEX"] == index
                );
                if (rowIndex > -1) {
                  tableData[rowIndex].processingDrawing = res.data.url; // 假设接口返回的文件路径是 res.data.fileUrl
                  tableData[rowIndex].processingDrawingName = res.data.fileName; // 假设接口返回的文件路径是 res.data.fileUrl
                }
                $(`#uploaded-${index}`).html(
                  `<a href="${res.data.url}" target="_blank">查看附件</a>`
                );
                console.log("文件上传成功:", res.data);
              } else {
                console.error("文件上传失败:", res.message);
              }
            },
            error: function () {
              // 上传失败的回调
              console.error("上传失败");
            },
          });
        },
      });

      if (data && data.id) {
        form.val("warehouseProductionOrderForm", data);
        admin.initDataSelect(
          "warehouse/warehouse/contract/list",
          {
            warehouseCustomerId: data.customerId,
          },
          "contractId",
          data.contractId,
          "合同编号",
          "contractName"
        );
        tableVal.reload({
          data: data.warehouseProductionOrderDetailList,
        });
      } else {
      }

      form.on("submit(formSubmit)", function (d) {
        let formData = { ...d.field };

        formData.warehouseProductionOrderDetailList =
          table.cache["purchasePlanFormTable"];
        console.log(formData);
        formData.remainingProductionSchedule =
          formData.warehouseProductionOrderDetailList.reduce(
            (acc, curr) => acc + Number(curr.requiredQuantity || 0),
            0
          );
        formData.processedQuantity = formData.remainingProductionSchedule;
        console.log(formData.remainingProductionSchedule);
        if (nowData.eventName == "add") {
          delete formData.id;
          admin.req(
            "warehouse/warehouse/productionOrder/add",
            JSON.stringify(formData),
            function (res) {
              layer.closeAll("loading");
              if (res.code == 200) {
                layer.msg(res.msg, { icon: 1 });
                table.reload("ProductionOrderTable");
                layer.closeAll("page");
              } else {
                layer.msg(res.msg, { icon: 2, time: 1000 });
              }
            },
            "POST",
            false,
            "application/json"
          );
        }
        //  else if (nowData.eventName == "edit") {
        //   admin.req(
        //     "enterprise/purchase/admin/purchasePlan/update",
        //     JSON.stringify(formData),
        //     function (res) {
        //       layer.closeAll("loading");
        //       if (res.code == 200) {
        //         layer.msg(res.msg, { icon: 1 });
        //         table.reload("purchasePlanTable");
        //         layer.closeAll("page");
        //       } else {
        //         layer.msg(res.msg, { icon: 2, time: 1000 });
        //       }
        //     },
        //     "PUT",
        //     false,
        //     "application/json"
        //   );
        // }
        return false;
      });
      $("#purchasePlanSuccess").click(() => {
        const formData = nowData.data;
        formData.planInfoList = table.cache["purchasePlanFormTable"];
        formData.status = "success";
        formData.reason = $("#reason").val();
        admin.req(
          "enterprise/purchase/admin/purchasePlan/audit",
          JSON.stringify(formData),
          function (data) {
            layer.closeAll("loading");
            if (data.code == 200) {
              layer.msg(data.msg, { icon: 1, time: 500 });
              table.reload("purchasePlanTable");
              layer.closeAll("page");
            } else {
              layer.msg(data.msg, { icon: 2, time: 1000 });
            }
          },
          "POST",
          false,
          "application/json"
        );
      });
      $("#purchasePlanFail").click(() => {
        const formData = nowData.data;
        formData.planInfoList = table.cache["purchasePlanFormTable"];
        formData.status = "fail";
        formData.reason = $("#reason").val();
        admin.req(
          "enterprise/purchase/admin/purchasePlan/audit",
          JSON.stringify(formData),
          function (data) {
            layer.closeAll("loading");
            if (data.code == 200) {
              layer.msg(data.msg, { icon: 1, time: 500 });
              table.reload("purchasePlanTable");
              layer.closeAll("page");
            } else {
              layer.msg(data.msg, { icon: 2, time: 1000 });
            }
          },
          "POST",
          false,
          "application/json"
        );
      });
      table.on("tool(purchasePlanFormTable)", function (obj) {
        var d = obj.data; // 获取当前行的数据
        var layEvent = obj.event; // 获取事件名（edit 或 del）
        if (obj.tr) {
          obj.tr.on("click", function (e) {
            e.preventDefault(); // 防止默认行为
          });
        }
        if (layEvent == "del") {
          const index = $(obj.tr[0]).data("index");
          let list = table.cache["purchasePlanFormTable"].filter((v) => {
            return v["LAY_TABLE_INDEX"] != index;
          });
          table.reload("purchasePlanFormTable", {
            data: list,
          });
        } else if (layEvent == "materialDetail") {
          let zindex = admin.formOpen({
            area: "90%",
            offset: "10%",
            title: "物料详情",
            content: $("#warehouseMaterialRequisitionRecordForm").html(),
            success: function () {
              // if (nowData.eventName === "detail") {
              //   admin.setFormDisable("#warehouseMaterialRequisitionRecordForm", true);
              // }
              // parentData.list = d.materialNumber;
              admin.req(
                "warehouse/warehouse/product/list",
                {
                  limit: 999999,
                  productCodes: d.materialNumber
                    ? d.materialNumber.split(",")
                    : [-1],
                },
                (res) => {
                  table.render({
                    elem: "#warehouseMaterialRequisitionRecordTable",
                    // url: config.base + "warehouse/warehouse/product/list",
                    data: res.data,
                    page: false,
                    cols: [
                      [
                        {
                          field: "productVariety",
                          align: "center",
                          title: "品种",
                        },
                        {
                          field: "productCode",
                          align: "center",
                          title: "客户成品料号",
                        },
                        {
                          field: "productSpecCode",
                          align: "center",
                          title: "规格",
                        },
                        {
                          field: "diameter",
                          align: "center",
                          title: "厚度/壁厚/直径",
                        },
                        { field: "width", align: "center", title: "宽度/外径" },
                        { field: "length", align: "center", title: "长度" },
                        {
                          field: "productMainUnit",
                          align: "center",
                          title: "成品单位",
                        },
                        {
                          align: "center",
                          toolbar:
                            "#warehouseMaterialRequisitionRecordTableBar",
                          title: "操作",
                        },
                      ],
                    ],
                  });
                }
              );
            },
          });
          $("#addMaterialInfo").click(() => {
            admin.formOpen({
              area: "90%",
              offset: "10%",
              title: "配置材料信息",
              content: $("#customerSku").html(),
              success: function () {
                table.render({
                  elem: "#customerSkuTable",
                  url: config.base + "warehouse/warehouse/product/list",
                  where: {
                    notIds: table.cache[
                      "warehouseMaterialRequisitionRecordTable"
                    ].map((v) => {
                      return v.id;
                    }),
                  },
                  page: true,
                  cols: [
                    [
                      { type: "checkbox" },
                      {
                        field: "productVariety",
                        align: "center",
                        title: "品种",
                      },
                      {
                        field: "productCode",
                        align: "center",
                        title: "客户成品料号",
                      },
                      {
                        field: "productSpecCode",
                        align: "center",
                        title: "规格",
                      },
                      {
                        field: "diameter",
                        align: "center",
                        title: "厚度/壁厚/直径",
                      },
                      { field: "width", align: "center", title: "宽度/外径" },
                      { field: "length", align: "center", title: "长度" },
                      {
                        field: "productMainUnit",
                        align: "center",
                        title: "成品单位",
                      },
                    ],
                  ],
                });
                $("#addCustomerSku").click(function () {
                  let checkData = table.checkStatus("customerSkuTable").data;
                  layer.close(parentData.zindex);
                  table.reload("warehouseMaterialRequisitionRecordTable", {
                    data: [
                      ...table.cache["warehouseMaterialRequisitionRecordTable"],
                      ...checkData,
                    ],
                  });
                });
              },
            });
          });
          $("#saveMaterialInfo").click(() => {
            let list = table.cache["purchasePlanFormTable"];
            let list1 = table.cache["warehouseMaterialRequisitionRecordTable"];

            list.forEach((v) => {
              if (v.productCode == d.productCode) {
                v.materialNumber = list1.map((v) => v.productCode).join(",");
              }
            });
            table.reload("purchasePlanFormTable", {
              data: list,
            });
            layer.close(zindex);
          });
          table.on(
            "tool(warehouseMaterialRequisitionRecordTable)",
            function (obj) {
              var d = obj.data; // 获取当前行的数据
              var layEvent = obj.event; // 获取事件名（edit 或 del）
              if (layEvent == "del111") {
                const index = $(obj.tr[0]).data("index");
                let list = table.cache[
                  "warehouseMaterialRequisitionRecordTable"
                ].filter((v) => {
                  return v["LAY_TABLE_INDEX"] != index;
                });
                table.reload("warehouseMaterialRequisitionRecordTable", {
                  data: list,
                });
              }
            }
          );
        }
      });

      $("#Configure").click(function () {
        if ($("#customerId").val()) {
          admin.formOpen({
            area: "90%",
            offset: "10%",
            title: "配置成品信息",
            content: $("#customerSku").html(),
            success: function () {
              table.render({
                elem: "#customerSkuTable",
                url: config.base + "warehouse/warehouse/product/list",
                where: {
                  customerId: $("#customerId").val(),
                  notIds: table.cache["purchasePlanFormTable"].map((v) => {
                    return v.id;
                  }),
                },
                page: true,
                cols: [
                  [
                    { type: "checkbox" },
                    { field: "productVariety", align: "center", title: "品种" },
                    {
                      field: "productCode",
                      align: "center",
                      title: "客户成品料号",
                    },
                    {
                      field: "productSpecCode",
                      align: "center",
                      title: "规格",
                    },
                    {
                      field: "diameter",
                      align: "center",
                      title: "厚度/壁厚/直径",
                    },
                    { field: "width", align: "center", title: "宽度/外径" },
                    { field: "length", align: "center", title: "长度" },
                    {
                      field: "productMainUnit",
                      align: "center",
                      title: "成品单位",
                    },
                  ],
                ],
              });
              $("#addCustomerSku").click(function () {
                let checkData = table.checkStatus("customerSkuTable").data;
                checkData = checkData.map((v) => {
                  v.productId = v.id;
                  return v;
                });
                layer.close(parentData.zindex);
                table.reload("purchasePlanFormTable", {
                  data: [...table.cache["purchasePlanFormTable"], ...checkData],
                });
              });
            },
          });
        } else {
          layer.msg("请选择提货订单编号", { icon: 2, time: 1000 });
        }
      });
    }
  );
</script>

<style>
  #warehouseProductionOrderForm .layui-form-label {
    width: 125px;
  }

  #warehouseProductionOrderForm .layui-input-block {
    margin-left: 155px;
  }

  #warehouseProductionOrderForm .layui-form-item .layui-inline {
    /* margin-bottom: 5px; */
    margin-right: 0px;
  }
</style>
